# 准备合并逻辑。。两个数据库字段统一
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

from django.conf import settings
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.models.mysql.mysql_user_model import UserModel, UserManager 
    from tanxi.models.mysql.mysql_article_model import ArticleModel
        
elif settings.DATABASE_TYPE == 'sqlite':
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserModel as UserModel
    from tanxi.models.sqlite.sqlite_user_model import SqliteUserManager as UserManager
    from tanxi.models.sqlite.sqlite_article_model import SqliteArticleModel as ArticleModel
else:
    raise ValueError("Unsupported database type specified in settings.")

from tanxi.client.Handler.Logger import log_info
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist


from demoPython.settings import db_config
from django.db.models import F

# 创建数据库引擎
engine = create_engine(f'mysql+mysqlconnector://{db_config["user"]}:{db_config["password"]}@{db_config["host"]}/{db_config["database"]}')
Session = sessionmaker(bind=engine)

# 功能类1 文章查询  
class ArticleQueryHandler():
    def __init__(self):
        self.session = Session()

    def query_articles(self,id=None,title=None, author_id=None,is_published=None):
        """
        查询文章，根据标题、作者和发布状态进行过滤。
        """
        # articles = ArticleModel.objects.all()
        articles = ArticleModel.objects.annotate(
                author_name=F('author__name')  # 使用双下划线访问关联模型的字段
            ).values(
                'id', 'title', 'content','author_name','publish_time','read_count','tags','updated_time', 'is_published'  # 选择需要的字段
            )
        if id:
            id = int(id)
            log_info(f"文章id {id}")
            articles = articles.filter(id=id)

        if title:
            articles = articles.filter(title__icontains=title)
        
        if author_id:
            articles = articles.filter(author__name__icontains=author_id)
        
        if is_published is not None:
                articles.is_published = is_published

        return articles



# 待改 字段丰富
class ArticleUpdateHandler:
    def update_or_create_article(self, article_data):
        """
        更新或创建文章。如果文章存在，则更新提供的字段；如果不存在，则创建新文章。
        :param article_data: 包含文章数据的字典
        :return: dict 返回操作结果，包括 article_id
        """
        if not article_data:
            raise ValueError("文章数据不能为空。")

        article_id = article_data.get('id')  # 前端可能传 'id' 或 'article_id'

        if article_id:
            try:
                # 尝试获取现有文章
                article = ArticleModel.objects.get(id=article_id)
                log_info(f"更新现有文章: ID={article_id}, 数据={article_data}")

                # 更新现有文章的字段
                for field, value in article_data.items():
                    if hasattr(article, field) and field != 'id':  # 排除 id 字段
                        setattr(article, field, value)
                article.updated_time = timezone.now()  # 更新时间戳
                article.save()
                return {'article_id': article.id, 'message': '文章更新成功'}

            except ObjectDoesNotExist:
                raise ValueError(f"文章 ID {article_id} 不存在。")
            except Exception as e:
                log_info(f"更新文章失败: {e}")
                raise ValueError(f"更新文章失败: {str(e)}")

        # 创建新文章
        log_info(f"创建新文章: 数据={article_data}")

        # 检查是否提供了 author_id（新文章必须提供 author_id）
        if 'author_id' not in article_data:
            raise ValueError("创建新文章时必须提供 author_id。")

        # 设置默认值
        defaults = {
            'title': '',
            'content': '',
            'is_published': False,
            'publish_time': timezone.now(),
            'read_count': 0,
            'tags': [],
            'updated_time': timezone.now()
        }
        defaults.update(article_data)
        defaults.pop('id', None)  # 移除 id，让 ORM 处理自增

        # 创建新文章
        try:
            article = ArticleModel.objects.create(**defaults)
            return {'article_id': article.id, 'message': '文章创建成功'}
        except Exception as e:
            log_info(f"创建文章失败: {e}")
            raise ValueError(f"创建文章失败: {str(e)}")
        

    def delete_article(self, id):
        """
        删除文章
        """
        ArticleModel.objects.filter(id=id).delete()
        return True
